package com.ctsi.offlinesupport.service;

import com.ctsi.commons.util.StringUtil;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.exception.ExceptionFactory;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.offlinesupport.app.rest.reponse.FlowMember;
import com.ctsi.offlinesupport.constant.FlowRole;
import com.ctsi.offlinesupport.dto.AllSupportorDTO;
import com.ctsi.offlinesupport.dto.AssterDTO;
import com.ctsi.offlinesupport.dto.AssterDepartDTO;
import com.ctsi.offlinesupport.dto.SupportorDTO;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.entity.OrganiseEntity;
import com.ctsi.organise.service.OrganiseEntityManager;
import com.ctsi.organise.service.UserExpertEntityService;
import com.ctsi.supportflow.app.entity.SupportInfo;
import com.ctsi.system.service.api.DictionayTreeServiceProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhangjw
 * @Date: 2018/11/8 03:43
 * @Description:
 */
@Service
public class SupportUtilService {
    private static final Logger logger = LoggerFactory.getLogger(SupportUtilService.class);
    @Autowired
    private DictionayTreeServiceProxy dictionayTreeServiceProxy;
    @Autowired
    private UserExpertEntityService userExpertEntityService;
    @Autowired
    private MybatisGenericDao dao;
    @Autowired
    private OrganiseEntityManager organiseEntityService;
    @Autowired
    private ExceptionFactory exceptionFactory;

    /**
     * 通过角色获取支撑人员列表（自动派单）
     * @param organId
     * @param expertTag
     * @return
     */
    public List<String> findSupportManager(String organId, String expertTag){
        return  userExpertEntityService.findSupportManager(organId,expertTag,"flow-supportor-role",5);
    }

    /**
     * 查询角色成员
     * @param roleId
     * @return
     */
    public List<String> findRoleMember(String roleId){
        return (List<String>) dao.queryForList(SupportInfo.class.getName()+".selectRoleMember", roleId);
    }

    public String finRoleMemberRandom(String roleId){
        List<String> ids = findRoleMember(roleId);
        if (UtilValidate.isEmpty(ids)) {
            return null;
        }
        if (UtilValidate.isNotEmpty(ids) && ids.size()>1) {
            Random random = new Random();
            int n = random.nextInt(ids.size());
            return ids.get(n);
        }

        return ids.get(0);

    }


    /**
     * 查询特定组织下，某一角色的所有人
     * @param roleId
     * @param organIds
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @Deprecated
    public Page<SupportorDTO> findSupportMan(String roleId,List<String> organIds,String userNameLike,int start,int pageSize){
        if(pageSize<0||pageSize>2000) {
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1) {
            Map<String,Object> param = new HashMap<>();
            if (UtilValidate.isNotEmpty(userNameLike)) {
                param.put("userNameLike","%"+userNameLike+"%");
            }
            param.put("roleId",roleId);
            param.put("organIds",organIds);
            UtilHttp.filterBlank(param);
            Page<SupportorDTO> page = dao.queryPage(SupportInfo.class.getName()+".findSupportor", param, start, pageSize);
            if (UtilValidate.isNotEmpty(page.getResult())) {
                for (SupportorDTO dto : page.getResult()) {
                    String organId = dto.getOrganId();
                    List<OrganiseEntity> exs = organiseEntityService.getOrganiseChain(organId);
                    List<String> organNames = exs.stream().map(ex -> ex.getPartyName()).collect(Collectors.toList());
                    dto.setOrganChainName(StringUtil.join(organNames,","));
                }
            }

            return page;
        } else{
            throw new RuntimeException("参数不正确 !!");
        }
    }

    /**
     * 根据角色类型和组织ID获取角色
     * @param roleType
     * @param organiseId
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    public Page<SupportorDTO> findRolePerson(String roleType,String organiseId,String userNameLike,int start,int pageSize){
        if(pageSize<0||pageSize>2000) {
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1) {
            Map<String,Object> param = new HashMap<>();
            if (UtilValidate.isNotEmpty(userNameLike)) {
                param.put("userNameLike","%"+userNameLike+"%");
            }
            param.put("roleType",roleType);
            param.put("organiseId",organiseId);
            UtilHttp.filterBlank(param);
            Page<SupportorDTO> page = dao.queryPage(SupportInfo.class.getName()+".findRoleMemberByRoleTypeAndOrganId", param, start, pageSize);
            if (UtilValidate.isNotEmpty(page.getResult())) {
                for (SupportorDTO dto : page.getResult()) {
                    String organId = dto.getOrganId();
                    List<OrganiseEntity> exs = organiseEntityService.getOrganiseChain(organId);
                    List<String> organNames = exs.stream().map(ex -> ex.getPartyName()).collect(Collectors.toList());
                    dto.setOrganChainName(StringUtil.join(organNames,","));
                }
            }

            return page;
        } else{
            throw new RuntimeException("参数不正确 !!");
        }
    }

    /**
     * 获取组织的政支主任角色
     * @return
     */
    public String findSupportMan(String organId){
        Page<SupportorDTO> dtos = findRolePerson(FlowRole.ZHUREN.value, organId,null,0,Page.DEFAULT_PAGE_SIZE);
        if (UtilValidate.isEmpty(dtos.getResult())) {
            // 没有找到政支主任角色
            exceptionFactory.throwObjectNotFound("900001");
        }
        if (dtos.getTotalCount() != 1) {
            logger.error("find mutil zhengzhizhuren role ,random one" );
            List<SupportorDTO> ts = dtos.getResult();
            Random random = new Random();
            int n = random.nextInt(ts.size());
            return ts.get(n).getUserId();
        }
        return dtos.getResult().get(0).getUserId();
    }

//    /**
//     * 获取部门下所有部门ID
//     * @param lft
//     * @param rgt
//     * @return
//     */
//    public List<String> findOrganIds (int lft,int rgt){
//        Map<String, Object> param = new HashMap<>();
//        param.put("lft",lft);
//        param.put("rgt",rgt);
//       return (List<String>) dao.queryForList(SupportInfo.class.getName()+".findSonOrganId",param);
//    }

    /**
     * 查询所有子孙组织
     * @param partyId
     * @return
     */
    public List<String> findOrganIds(String partyId){

        return (List<String>) dao.queryForList(SupportInfo.class.getName()+".selectAllSonOrganId",partyId );
    }

    /**
     * 查询协同部门负责人
     * @param curUserId
     * @param departNameLike
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    public Page<AssterDepartDTO> queryAssterLeader(String roleType,String curUserId,String departNameLike,String userNameLike,int start,int pageSize){
        if (UtilValidate.isEmpty(curUserId) || UtilValidate.isEmpty(roleType)) {
            exceptionFactory.throwInternalError();
        }
        if(pageSize<0||pageSize>2000) {
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1) {
            Map<String,Object> param = new HashMap<>();
            if (UtilValidate.isNotEmpty(userNameLike)) {
                param.put("personNameLike","%"+userNameLike+"%");
            }
            if (UtilValidate.isNotEmpty(departNameLike)) {
                param.put("departNameLike","%"+departNameLike+"%");
            }

            // 获取当前登陆用户的组织ID
            Organise organise = OrganiseFactoryBean.getInstance().getPersonServiceProxy().getOrganise4User(curUserId);
//            List<String> ll = new ArrayList<>();
//            ll.add(organise.getPartyId());
//            ll.addAll(findOrganIds(organise.getPartyId()));
            UtilHttp.filterBlank(param);
            param.put("organiseId", organise.getPartyId());
            param.put("roleType",roleType);
            Page<AssterDepartDTO> page = dao.queryPage(SupportInfo.class.getName()+".findAssertUserLeader", param, start, pageSize);

            if (UtilValidate.isNotEmpty(page.getResult())) {
                for (AssterDepartDTO dto : page.getResult()) {
                    String organId = dto.getDepartId();
                    List<OrganiseEntity> exs = organiseEntityService.getOrganiseChain(organId);
                    List<String> organNames = exs.stream().map(ex -> ex.getPartyName()).collect(Collectors.toList());
                    dto.setDepartName(StringUtil.join(organNames,","));
                }
            }
            return page;
        } else{
            throw new RuntimeException("参数不正确 !!");
        }

    }

    /**
     * 查询部门专家角色列表
     * @param roleType
     * @param curUserId
     * @param start
     * @param pageSize
     * @return
     */
    public Page<AssterDTO> findAssert(String roleType,String curUserId,String userNameLike,int start,int pageSize){
        if (UtilValidate.isEmpty(curUserId) || UtilValidate.isEmpty(roleType)) {
            exceptionFactory.throwInternalError();
        }
        if(pageSize < 0||pageSize > 2000) {
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1) {
            Map<String,Object> param = new HashMap<>();
            if (UtilValidate.isNotEmpty(userNameLike)) {
                param.put("userNameLike","%"+userNameLike+"%");
            }
            // 获取当前登陆用户的组织ID
            Organise organise = OrganiseFactoryBean.getInstance().getPersonServiceProxy().getDepart4User(curUserId);
            param.put("departId", organise.getPartyId());
            param.put("roleType",roleType);
            UtilHttp.filterBlank(param);
            Page<AssterDTO> page = dao.queryPage(SupportInfo.class.getName()+".findAsster", param, start, pageSize);
            return page;
        } else{
            throw new RuntimeException("参数不正确 !!");
        }
    }

    /**
     * 查询所有支撑经理
     * @param organId
     * @param personNameLike
     * @param start
     * @param pageSize
     * @return
     */
    public Page<AllSupportorDTO> findAllSuportDTO(String organId,String personNameLike,String roleType,int start,int pageSize){
        Map<String,Object> params = new HashMap<>();
        params.put("organId",organId);
        params.put("personNameLike",personNameLike);
        params.put("roleType",roleType);
        return dao.queryPage(SupportInfo.class.getName()+".findAllSupport", params, start, pageSize);
    }

    /**
     * 判断该用户是否省里的
     * @param userId
     * @return
     */
    public boolean isProvice(String userId){
       Long count = (Long) dao.queryForObject(SupportInfo.class.getName()+".isProvice",new HashMap<String,Object>(){{
            put("userId",userId);
        }});

       if (count > 0) {
           return true;
       }
        return false;
    }

    /**
     * 查询派单角色
     * @return
     */
    public List<FlowMember> findFlowMember(String userId){
        Map<String,Object> params = new HashMap<>();
        if (isProvice(userId)) {
            params.put("roleTypes", Stream.of("zhongxinzhuren").collect(Collectors.toSet()));
        } else {
            params.put("roleTypes", Stream.of("zhongxinzhuren","flow-zhuren-role").collect(Collectors.toSet()));
        }
        return (List<FlowMember>) dao.queryForList(SupportInfo.class.getName()+".findSupportRole4Send",params);
    }

}
